package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.*;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper detailMapper;

    /*
    SELECT *
    FROM tb_spu
    WHERE `name` LIKE "%小%" AND saleable = 1
    ORDER BY update_time DESC
    LIMIT 0, 10
     */
    public PageResult<SpuDTO> querySpuByPage(String key, Integer page, Integer rows, Boolean saleable) {
        // 1.分页
        PageHelper.startPage(page, rows);

        // 2.搜索条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 2.1.关键字搜索 `name` LIKE "%小%"
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("name", "%" + key + "%");
        }
        // 2.2.上下架搜索
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }
        // 2.3.排序
        example.setOrderByClause("update_time DESC");

        // 3.发起请求
        List<Spu> list = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }

        // 4.解析结果
        // 4.1.处理分页
        PageInfo<Spu> info = new PageInfo<>(list);
        // 4.2.转换DTO
        List<SpuDTO> dtoList = BeanHelper.copyWithCollection(list, SpuDTO.class);
        // 4.3.处理分类和品牌的名称
        handleCategoryAndBrandName(dtoList);
        return new PageResult<>(info.getTotal(), info.getPages(), dtoList);
    }

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    private void handleCategoryAndBrandName(List<SpuDTO> dtoList) {
        for (SpuDTO spuDTO : dtoList) {
            // 处理分类名称
            List<Long> categoryIds = spuDTO.getCategoryIds();

//            List<CategoryDTO> categoryDTOList = categoryService.queryByIds(categoryIds);
//            StringBuilder sb = new StringBuilder();
//            for (CategoryDTO categoryDTO : categoryDTOList) {
//                sb.append(categoryDTO.getName()).append("/");
//            }
//            sb.deleteCharAt(sb.length() - 1);

            String name = categoryService.queryByIds(categoryIds)
                    .stream()
                    .map(CategoryDTO::getName)
                    .collect(Collectors.joining("/"));
            spuDTO.setCategoryName(name);


            // 处理品牌名称
            Long brandId = spuDTO.getBrandId();
            BrandDTO brandDTO = brandService.queryById(brandId);
            spuDTO.setBrandName(brandDTO.getName());
        }
    }

    @Autowired
    private SkuMapper skuMapper;

    @Transactional
    public void saveGoods(SpuDTO spuDTO) {
        try {
            // 1.写入Spu
            // 1.1.转换DTO
            Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
            // 1.2.初始化默认值，默认下架
            spu.setSaleable(false);
            // 1.3.新增spu
            spuMapper.insertSelective(spu);

            // 2.写入SpuDetail
            // 2.1.转换DTO
            SpuDetail spuDetail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
            // 2.2.填充数据
            spuDetail.setSpuId(spu.getId());
            // 2.3.写入数据库
            detailMapper.insertSelective(spuDetail);

            // 3.写入Sku表
            saveSku(spuDTO, spu);
        } catch (Exception e) {
            log.error("新增商品失败！原因：{}", e.getMessage(), e);
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL, e);
        }
    }

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Transactional
    public void updateSaleable(Long id, Boolean saleable) {
        try {
            // 修改spu中的saleable， update tb_spu set saleable = saleable where id = 1
            Spu spu = new Spu();
            spu.setId(id);
            spu.setSaleable(saleable);
            int count = spuMapper.updateByPrimaryKeySelective(spu);
            if (count != 1) {
                throw new RuntimeException("更新spu失败！");
            }
            // 修改sku中的标识: enable, update tb_sku set enable = 1 where spu_id = 1
            // 更新的内容
            Sku sku = new Sku();
            sku.setEnable(saleable);
            // 更新的条件
            Example example = new Example(Sku.class);
            example.createCriteria().andEqualTo("spuId", id);
            skuMapper.updateByExampleSelective(sku, example);

            // 判断是上架还是下架，使用不同的routingKey
            String routingKey = saleable ? MQConstants.RoutingKey.ITEM_UP_KEY : MQConstants.RoutingKey.ITEM_DOWN_KEY;
            // 发送MQ消息，通知其它服务
            amqpTemplate.convertAndSend(MQConstants.Exchange.ITEM_EXCHANGE_NAME, routingKey, id);
        } catch (Exception e) {
            log.error("更新商品数据失败，原因：{}", e.getMessage(), e);
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }

    public SpuDetailDTO queryDetailBySpuId(Long id) {
        SpuDetail spuDetail = detailMapper.selectByPrimaryKey(id);
        if (spuDetail == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail, SpuDetailDTO.class);
    }

    public List<SkuDTO> querySkuBySpuId(Long id) {
        Sku sku = new Sku();
        sku.setSpuId(id);
        List<Sku> list = skuMapper.select(sku);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        Long spuId = spuDTO.getId();
        if (spuId == null) {
            throw new RuntimeException("商品id不存在");
        }
        // 查询sku（判断sku是否存在）
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        int count = skuMapper.selectCount(sku);
        if (count != 0) {
            // 删除sku
            skuMapper.delete(sku);
        }
        // 更新spu, 把不需要更新的字段设置为null，避免更新
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        spu.setSaleable(null);
        spu.setCreateTime(null);
        spuMapper.updateByPrimaryKeySelective(spu);

        // 更新spuDetail
        SpuDetailDTO detailDTO = spuDTO.getSpuDetail();
        SpuDetail detail = BeanHelper.copyProperties(detailDTO, SpuDetail.class);
        detailMapper.updateByPrimaryKeySelective(detail);

        // 新增sku
        saveSku(spuDTO, spu);
    }

    private void saveSku(SpuDTO spuDTO, Spu spu) {
        List<SkuDTO> skuDTOS = spuDTO.getSkus();
        // 转换skuDTO到sku
        List<Sku> skuList = new ArrayList<>();
        for (SkuDTO skuDTO : skuDTOS) {
            Sku sku = BeanHelper.copyProperties(skuDTO, Sku.class);
            sku.setEnable(false);
            sku.setSpuId(spu.getId());
            skuList.add(sku);
        }
        // 写入数据库
        skuMapper.insertList(skuList);
    }

    public SpuDTO querySpuById(Long spuId) {
        // 查询spu
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if (spu == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        // 转换DTO
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);

        // 查询sku
        spuDTO.setSkus(querySkuBySpuId(spuId));

        // 查询spuDetail
        spuDTO.setSpuDetail(queryDetailBySpuId(spuId));

        // 查询商品相关的分类
        spuDTO.setCategories(categoryService.queryByIds(spuDTO.getCategoryIds()));

        // 查询商品相关的品牌
        spuDTO.setBrand(brandService.queryById(spuDTO.getBrandId()));

        return spuDTO;
    }

    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        List<Sku> list = skuMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    @Transactional
    public void minusStock(Map<Long, Integer> skuMap) {
        for (Map.Entry<Long, Integer> entry : skuMap.entrySet()) {
            Long skuId = entry.getKey();
            Integer num = entry.getValue();
            try {
                skuMapper.minusStock(skuId, num);
            }catch (Exception e){
                log.error("商品库存不足！skuId为:{}", skuId);
                throw new LyException(ExceptionEnum.STOCK_NOT_ENOUGH_ERROR);
            }
        }
    }
}
